package cn.yr.clock.handler;

import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import cn.yr.common.exception.exception.ParameterException;
import cn.yr.common.exception.exception.PreAuthorizeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * token处理器
 */
@Slf4j
@Component
public class TokenHandler {

    private String signature = "clockIn";

    public String generateToken(Long userId) {
        HashMap<String, Object> map = new HashMap<>(2);
        map.put("expireTime", System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 15);
        map.put("userId", userId);
        return JWTUtil.createToken(map, signature.getBytes());
    }

    public Long getUserId(String token) {
        boolean verify = JWTUtil.verify(token, signature.getBytes());
        if (!verify) {
            log.error("错误token,验证失败,{}", token);
            throw new PreAuthorizeException("错误token，请重新登录");
        }
        JWTPayload payload = JWTUtil.parseToken(token).getPayload();
        JSONObject claimsJson = payload.getClaimsJson();
        Long expireTime = claimsJson.getLong("expireTime");
        if (System.currentTimeMillis() > expireTime) {
            log.error("token已过期,验证失败,{},{}", System.currentTimeMillis(), token);
            throw new PreAuthorizeException("登录过期，请重新登录");
        }
        return claimsJson.getLong("userId");
    }

}
